<?php

include "include/ini.php";
if ($has_db_settings) {
    $users = mysql_select_array("SELECT * FROM `users`  ORDER BY `short_name` ASC");
    $months = array("Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь");
    $days = array("Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб");
} elseif (!$has_db_settings) {
    redirect("setup.php");
    die;
}
if (post('update_name')) {
    set_name();
    redirect(BASE_URL);
}
if (get('send')) {
    send_order();
}
$year = date("Y");
$month = get('month', date("m"));
$dates = array();
$i = 0;
$user_info = auth();
while ($i++ < date("t", strtotime($year . "-" . $month))) {
    $i = $i < 10 ? "0" . $i : $i;
    $dates[$i]['date'] = $year . "-" . $month . "-" . $i;
    $dates[$i]['day'] = date('w', strtotime($dates[$i]['date']));
}
$food = mysql_select_array("SELECT * FROM `food` WHERE `month` = '" . $year . $month . "'");
$food_ = array();
foreach ($food as $key => $val) {
    if ($food[$key]['uid']) {
        $food_[$val['uid']][$val['date']] = $val['order'];
    }
}
$food = $food_;
foreach ($dates as $k => $date) {
    $total[$date['date']] = array('1' => 0, '0.4' => 0, '0.5' => 0);
}
foreach ($users as $key => $user) {
    foreach ($dates as $k => $date) {
        $order = isset($food[$user['id']][$date['date']]) ? $food[$user['id']][$date['date']] : 0;
        if ($order) {
            $total[$date['date']][$order]++;
        }

        $food[$user['id']][$date['date']] = $order;
    }
    $usertotal = mysql_select_array("SELECT `order` FROM `food` WHERE `uid` = " . $user['id'] . " AND `month` = " . $year . $month . " ");
    $summary = array("0.4" => 0, "0.5" => 0, "cash" => 0);
    foreach ($usertotal as $ord) {
        if (in_array($ord['order'], array("0.4", "1"))) {
            $summary['0.4']++;
            $summary['cash']+=10;
        }
        if (in_array($ord['order'], array("0.5", "1"))) {
            $summary['0.5']++;
            $summary['cash']+=15;
        }
    }
    $users[$key]['summary'] = $summary;
}
$order_options = array(""=> 0, "0"=> 0, "0.4" => "П", "0.5" => "В", "1" => "Ц");
$prev_m = $month - 1;
$prev_m = strlen($prev_m) < 2 ? "0" . $prev_m : $prev_m;
$prev_month_link = $prev_m == date('m') ? BASE_URL : BASE_URL . "?month=" . $prev_m;
$next_m = $month + 1;
$next_m = strlen($next_m) < 2 ? "0" . $next_m : $next_m;
$next_month_link = $next_m == date('m') ? BASE_URL : BASE_URL . "?month=" . $next_m;
$total = get_totals($month);
$today_menu = mysql_value("SELECT `menu` FROM `date` WHERE `date` = '" . date("Y-m-d") . "'");
$today_menu = unserialize($today_menu);
include ROOT_PATH . 'tpl/header.php';
include ROOT_PATH . 'tpl/' . basename(__FILE__);
include ROOT_PATH . 'tpl/footer.php';